<!-- 登录页 -->
<template>
	<view>
		<form @submit="handleSubmit">
			<view class="get-user">
				<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					<image class="avatar" :src="avatarUrl" style="width: 112rpx !important;"></image>
					<view style="margin-top: 40rpx;">点击获取用户头像</view>
				</button>
				<view class="nickname">
					<view style="width: 120rpx;">昵称</view>
					<input type="nickname" name="nickname" placeholder="点击选择昵称" />
				</view>
				<view class="nickname2 flex-between">
					<view class="flex-align-center">
						<view style="width: 120rpx;">电话</view>
						<!-- //是否开启短信验证  1-开启，不开启则不能输入 -->
						<input type="number" maxlength="11" v-model="phone" class="font-overflow" placeholder="点击修改电话" @input="inputClick" :disabled="noteInfo != 1" />
					</view>
					<!-- 将获取到的手机号直接复制给input的mobile -->
					<button open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber" class="btn_phone">获取手机号</button>
				</view>
				<view class="flex-columns content" v-if="(noteInfo == 1 && inputPhone == mobile && mobile) || (noteInfo == 1 && inputPhone && !mobile)">
					<view class="flex-between">
						<view class="flex-align-center title">
							<text>验证码</text>
							<!-- 先监听到手机粘贴板的内容，才能做判断，否则用户体验不好 -->
							<!-- @focus="getCodeClick" -->
							<input
								type="number"
								adjust-position="flase"
								v-model="codes"
								maxlength="6"
								placeholder="输入验证码"
								class="box-input"
								placeholder-style="color: #c4c4c4;"
							/>
						</view>
						<!-- 发送验证码 -->
						<view :class="isDisabled == false ? 'verification-code flex' : 'verification-codes flex'" @click="sendInfo">{{ text }}</view>
					</view>
				</view>
				<view class="submit-userinfo">
					<!-- 获取头像登录 -->
					<view style="text-align: center;"><button type="primary" form-type="submit" size="mini" class="logins ">登录授权</button></view>

					<view style="text-align: center;margin-top: 30rpx;">
						<button type="default" @click="getUserProfile" hover-class="sunui-hover" size="mini" class="falls">默认登录</button>
					</view>
				</view>
			</view>
		</form>
	</view>
</template>

<script>
import antiThrottling from '@/utils/antiThrottling.js';

export default {
	data() {
		return {
			system: {},
			nickName: '',
			avatarUrl: '/static/avatar.png',
			mobile: '',
			// 是否登录页进入
			isRenovate: 0,
			// 是否团购商品详情页进入
			isGroup: 0,
			// 是否发布页进入
			isNeed: 0,

			// 产品id
			goodsId: '',
			uids: '',

			//是否开启  1-开启
			noteInfo: '',

			// 验证码
			codes: '',

			// 手机号
			phone: '',
			text: '发送验证码',
			time: 60,
			isDisabled: false,
			getnoteCode: '', //验证码返回

			inputPhone: '' ,//输入框 ——输入的手机号
			unionid:''
		};
	},
	onLoad(options) {
		this.isNeed = options.isNeed;
		this.isGroup = options.isGroup;
		this.goodsId = options.goods_id;
		this.uids = options.uid;
		this.isRenovate = options.isRenovate;
		
	},
	onShow() {
		
		this.notes();
		//解锁防抖/节流 当点击一次支付按钮时，锁定按钮（从而达到只能响应一次事件）  在支付页面调用
		antiThrottling.releaseKey('submit');
	},
	onReady() {
		this.$sun.title('登录授权');
	},
	methods: {
		
		// 系统设置
		async system() {
			const result = await this.$http.get({
				url: this.$api.system
			});
			if (result.errno == 0) {
				uni.setStorageSync('system', result.data);
			}
		},
		// 电话输入input事件
		inputClick(e) {
			this.inputPhone = e.detail.value;
			console.log('this.inputPhone!=this.mobile', this.inputPhone != this.mobile, 'this.noteInfo', this.noteInfo);
		},
		// 获取是否开启短信验证
		async notes() {
			const result = await this.$http.get({
				url: this.$api.noteConfig,
				data: {}
			});
			if (result.errno == 0) {
				//是否开启  note_open  1-开启
				this.noteInfo = result.data.note_open;
				console.log('this.noteInfo1111111111', this.noteInfo);
			}
		},
		// 发送验证码
		sendInfo() {
			if (!this.phone) {
				this.$sun.toast('手机号不能为空');
				return false;
			} else if (!/^1[3456789]\d{9}$/.test(this.phone)) {
				this.$sun.toast('请输入有效的手机号');
				return false;
			} else {
				antiThrottling.uniDoFunc({
					// 键名
					key: 'submit',
					success: async () => {
						//锁定
						antiThrottling.lockKey('submit');
						this.sendMobiles();
					}
				});
			}
		},
		// 发送验证码
		async sendMobiles() {
			const result = await this.$http.get({
				url: this.$api.sendMobile,
				data: {
					// 手机号码
					telphone: this.phone
				}
			});
			if (result.errno == 0) {
				this.getnoteCode = result.data;
				console.log('getnoteCode=', this.getnoteCode);
				//记秒数
				let time = this.time;
				this.isDisabled = true;
				const timer = setInterval(() => {
					if (time == 0) {
						clearInterval(timer); //清除定时器后，以下都是恢复原始状态
						this.isDisabled = false;
						this.text = '发送验证码';
						time = this.time;
						antiThrottling.releaseKey('submit');
					} else {
						this.text = `已发送（${time}）`;
						time--; //倒计时的实现，利用递减
					}
				}, 1000);
			} else {
				antiThrottling.releaseKey('submit');
				this.$sun.toast(result.message);
			}
		},
		// 获取焦点
		getCodeClick(){
			// 获取 粘贴板中的内容
			if(this.getnoteCode && !this.codes){
				console.log('粘贴板中的内容this.getnoteCode111',this.getnoteCode);
				let that=this
				uni.getClipboardData({
					success: function(res) {
						console.log('粘贴板中的内容222：', res.data,'that.getnoteCode',that.getnoteCode);
						if(that.getnoteCode==res.data){
							that.codes=res.data
							console.log("that.codes333=",that.codes)
						}
					},
					fail: function(err) {
						console.log('获取粘贴板内容失败：', err);
					}
				});
			}
		},
		// 获取手机号
		onGetPhoneNumber(e) {
			var _that = this;
			// 用户点击了接受
			if (e.detail.errMsg == 'getPhoneNumber:ok') {
				let encryptedData = e.detail.encryptedData;
				let errMsg = e.detail.errMsg;
				let iv = e.detail.iv;
				const code = e.detail.code;
				_that.cc = code;
				_that.getKeyByCode(_that.cc, encryptedData, iv);
			} else {
				/* uni.switchTab({
					url: '/pages/index/index'
				}); */
			}
		},
		// 获取手机号解密接口
		async getKeyByCode(code, encryptedData, iv) {
			const result = await this.$http.get({
				url: this.$api.getTelphone,
				data: {
					code: code
				}
			});
			if (result.errno == 0) {
				console.log('data', result.data);
				this.mobile = result.data.phone_info.phoneNumber;
				this.phone = this.mobile;
				this.inputPhone = this.mobile; // 为了获取手机号同步不展示验证码
			}
		},
		handleSubmit(e) {
			// 提交到接口
			const val = e.detail.value;
			this.nickname = val.nickname;
			if (!this.nickname || !this.phone) {
				uni.showModal({
					title: '温馨提示',
					content: `请输入用户名字，以及点击获取头像和手机号`,
					showCancel: false
				});
				return;
			}
			this.getUserProfile();
		},
		// 选择头像
		onChooseAvatar(e) {
			const { avatarUrl } = e.detail;
			this.xixixi(avatarUrl);
		},
	
		async xixixi(avatarUrl) {
			console.log(avatarUrl)
			uni.uploadFile({
				url: this.$api.uploadImg, //后台接口
				filePath: avatarUrl,
				
				name: 'file',
				formData: {
				
				},
			
				//成功的回调
				success: uploadFileRes => {
					var resuploadFileRes = JSON.parse(uploadFileRes.data);
					this.avatarUrl = resuploadFileRes.data;
					this.avatar = resuploadFileRes.data;
					uni.showToast({
						title: '头像上传成功！',
						icon: 'none',
						duration: 1000
					});
				},
				fail:(res)=>{
					console.log(res)
				}
			});
		},

		// 微擎的话自带获取用户信息,不需要重新获取code(所以都写在APP - onLaunch那里)
		handleUnAuth() {
			wx.navigateBack();
		},

		getUserProfile() {
			console.log(uni.getStorageSync('pid'),'uid============')
			if (!this.phone) {
				this.$sun.toast('请先完成获取手机号');
				return;
			} 
			else if (!/^1[3456789]\d{9}$/.test(this.phone)) {
				this.$sun.toast('请输入有效的手机号');
				return false;
			} 
			else if ((this.noteInfo == 1 && this.inputPhone == this.mobile && this.mobile &&!this.codes) || (this.noteInfo == 1 && this.inputPhone && !this.mobile&&!this.codes)) {
				this.$sun.toast('请输入验证码');
				return;
			} else if (this.getnoteCode && this.getnoteCode != this.codes) {
				this.$sun.toast('验证码错误，请重试');
				return;
			} else {
				uni.setStorageSync('mobile', this.phone);
				wx.login({
					provider: 'weixin',
					success: async res => {
						const openInfo = await this.$http.get({
							url: this.$api.getOpenId,
							data: {
								code: res.code
							}
						});
						if (openInfo.errno == 0) {
							let key = openInfo.data.session_key;
							var openid = openInfo.data.openid; //openid 用户唯一标识
							this.unionid = openInfo.data.unionid
							// 设置openid（先用微信的wx.login方法 再调用后端返回获取openid接口（传code)
							wx.setStorageSync('openid', openid);
							wx.setStorageSync('code', res.code);

							setTimeout(() => {
								uni.request({
									url: this.$api.register,
									method: 'GET',
									data: {
										telphone: this.phone,
										unionid:this.unionid,
										/*  * 新增微信用户
										 * @param openid
										 * @param avatar 头像
										 * @param nickname 昵称
										 * @param dy_uid 抖音uid */
										// 微信用户opendid
										openid: wx.getStorageSync('openid'),
										// 微信用户昵称
										// nickname: user.nickName,
										// 独立小程序需要
										nickname: this.nickname ? this.nickname : '默认昵称',
										// 微信用户头像
										avatar: this.avatarUrl ? this.avatarUrl : this.$img.avatar,
										// 分销pid
										// pid : pid
										pid: uni.getStorageSync('pid') !== null && uni.getStorageSync('pid') !== undefined && uni.getStorageSync('pid') !== '' ? uni.getStorageSync('pid') : ''

									},
									success: res => {
										console.log('uid', res.data);
										wx.setStorageSync('uid', res.data.data);
										if (res.errMsg == 'request:ok') {
											wx.setStorageSync('isTrue', 1);
											this.$sun.toast('登录成功');
											this.userInfos();
										}
									},
									fail: err => {
										uni.showModal({
											title: '错误',
											content: `访问公众平台接口失败, 错误: invalid appsecret, view more at http://t.cn/RAEkdVq, hints: [ req_id: WeMfdZyFe-D3JW7 ],错误详情：无效的appsecret`,
											showCancel: false
										});
									},
									complete: info => {
										// 由于wx.getUserProfile被删除了，所以获取不到res.user
										// wx.setStorageSync('userInfo', user);
									}
								});
							}, 500);
						} else {
							setTimeout(() => {
								console.log('失败', res);
							}, 2000);
						}
					}
				});
			}
		},
		
		
		// 用户信息
		async userInfos() {
			const result = await this.$http.get({
				url: this.$api.userInfo,
				data: {
					// 用户id
					uid: uni.getStorageSync('uid'),
					// 上级id
					// pid: ''
				}
			});
			if (result.errno == 0) {
				uni.setStorageSync('user', result.data);
				this.$sun.navRe('/pages/mine/mine');
			}
		},
		
		
		
	}
};
</script>

<style lang="scss">
/deep/ button::after {
	border: none;
}
.get-user {
	background-color: #fff;
	padding-top: 80rpx;
	height: 100vh;
	.submit-userinfo {
		margin: 40rpx 0;
		margin-top: 260rpx;

		button {
			display: inline-flex !important;
			align-items: center;
			justify-content: center;
			height: 70rpx;
			line-height: 1;
			vertical-align: middle;
			-webkit-appearance: none;
			-webkit-text-size-adjust: 100%;
			box-sizing: border-box;
			font-size: 32rpx;
			white-space: nowrap;
			margin: 0;
			padding: 0rpx 120rpx;
			overflow: visible;
			border-radius: 10rpx;
			font-weight: bold;
			margin: auto;
		}
		.logins,
		.falls {
			width: 370rpx;
		}
		.logins {
			background-color: #3375f7;
			text-align: center;
		}
		.falls {
			color: #3375f7;
			margin-top: 20rpx;
			font-weight: initial;
		}
	}

	.avatar-wrapper {
		padding: 0;
		
		border-radius: 16rpx;
		margin-bottom: 80rpx;
		color: #9b9b9b;
		background: #ffffff;
	}

	.avatar {
		display: block;
		width: 112rpx;
		height: 112rpx;
		margin: 20rpx auto;
		border-radius: 20rpx;
	}

	.nickname {
		display: flex;
		align-content: center;
		border-bottom: 2rpx solid #f7f7f7;
		padding: 32rpx;
	}
	.nickname2 {
		display: flex;
		align-content: center;
		border-bottom: 2rpx solid #f7f7f7;
		padding: 20rpx 32rpx;
		.btn_phone {
			width: 220rpx;
			text-align: right;
			color: #666666;
			background-color: #fff;
			font-size: 28rpx;
			padding: 0rpx;
		}
	}

	.content {
		padding: 24rpx 0rpx;
		margin: 0rpx 30rpx;
		border-bottom: 2rpx solid #f7f7f7;
		.title {
			text {
				width: 120rpx;
				// padding-top: 46rpx;
			}
			image {
				width: 44rpx;
				height: 44rpx;
				margin-right: 22rpx;
			}
		}
		.box-input {
			display: flex;
			flex: 1;
			
		}
		.box-input-password {
			font-size: 28rpx;
			padding-top: 46rpx;
		}
		.verification-code,
		.verification-codes {
			
			font-size: 28rpx;
			color: #ffffff;
			border-radius: 10rpx;
			width: 188rpx;
			height: 60rpx;
			margin-right: 45rpx;
		}
		.verification-code {
			background: #3375f7;
		}
		.verification-codes {
			background: #808080;
		}
	}
}
</style>
